<template>
  <a-modal
    :title="`修改密码【`+nickname+`】`"
    :visible="visible"
    :width="width"
    :confirmLoading="confirmLoading"
    @ok="handleModalOk"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item
        label="原密码"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-input-password
          v-decorator="[
            'oldPassword',
            {
              rules: [
                {
                  required: true,
                  message: '请输入原密码'
                },
                {
                  validator: passwordIsRight
                }
              ]
            }
          ]"
          placeholder="请输入原密码"
        />
      </a-form-item>
      <a-form-item
        label="新密码"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-input-password
          v-decorator="[
            'newPassword',
            {
              rules: [
                {
                  required: true,
                  message: '必须包含数字、特殊符号、字母，长度8-16',
                  validator: validateToNextPassword
                }
              ]
            }
          ]"
          placeholder="请输入新密码"
          @blur="handleConfirmBlur"
        />
      </a-form-item>
      <a-form-item
        label="再次输入密码"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-input-password
          v-decorator="[
            'confirmPassword',
            {
              rules: [
                {
                  required: true,
                  message: '请再次输入密码'
                },
                {
                  validator: compareToFirstPassword
                }
              ]
            }
          ]"
          placeholder="请再次输入密码"
          @blur="handleConfirmBlur"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import api from '../../api/index'
import { emptyObject, passwordRule } from '@/utils/samsUtil'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'PasswordModifyModal',
  data () {
    return {
      visible: false,
      confirmLoading: false,
      width: 600,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this)
    }
  },
  computed: {
    ...mapGetters(['nickname'])
  },
  methods: {
    ...mapActions(['Logout']),
    showModal () {
      this.rest()
      this.visible = true
    },
    hide () {
      this.visible = false
    },
    passwordIsRight (rule, value, callback) {
      if (emptyObject(value)) {
        callback()
        return
      }
      const b = passwordRule(value)
      if (!b) {
        // eslint-disable-next-line
        callback('必须包含数字、特殊符号、字母，长度8-16')
      } else {
        callback()
      }
    },
    handleConfirmBlur (e) {
      this.form.validateFields(['newPassword', 'confirmPassword'], (errors, values) => {
        console.log(errors, values)
      })
    },
    compareToFirstPassword (rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('newPassword')) {
        // eslint-disable-next-line
        callback('您输入的两个密码不一致')
      } else {
        callback()
      }
    },
    validateToNextPassword (rule, value, callback) {
      const b = passwordRule(value)
      if (!b) {
        // eslint-disable-next-line
        callback('必须包含数字、特殊符号、字母，长度8-16')
      } else {
        const form = this.form
        if (value && this.confirmDirty) {
          form.validateFields(['confirm'], { force: true })
        }
        callback()
      }
    },
    handleLogout () {
      this.Logout({}).then(() => {
        setTimeout(() => {
          window.location.reload()
        }, 100)
      }).catch(err => {
        this.$message.error({
          title: '错误',
          description: err.message
        })
      })
    },
    // 确定按钮--保存
    handleModalOk () {
      this.form.validateFields((error, values) => {
        if (error === null) {
          this.axios.post(api.UpdatePassword, values)
            .then((response) => {
              if (response.code === 200) {
                this.hide()
                this.modifySuccess()
              } else {
                this.$message.error('修改密码失败：' + response.message)
              }
            })
            .catch((error) => {
              this.$message.error('修改密码异常：' + error)
            })
        }
      })
    },
    // 取消按钮
    handleCancel () {
      this.hide()
    },
    // form表单数据初始化方法
    rest () {
      this.form.resetFields()
    },
    modifySuccess () {
      const _this = this
      let secondsToGo = 5
      const modal = this.$success({
        title: '密码修改成功，请重新登录',
        content: `即将返回登录页面，倒计时【${secondsToGo}】秒！！！`,
        okText: `前去登录`,
        onOk: function () {
          _this.handleLogout()
        }
      })
      const interval = setInterval(() => {
        secondsToGo -= 1
        modal.update({
          content: `即将返回登录页面，倒计时【${secondsToGo}】秒！！！`
        })
      }, 1000)
      setTimeout(() => {
        clearInterval(interval)
        modal.destroy()
        _this.handleLogout()
      }, secondsToGo * 1000)
    }
  }
}
</script>
